package com.honghu.villagepost.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.honghu.villagepost.MainActivity;
import com.honghu.villagepost.R;
import com.honghu.villagepost.api.ApiService;
import com.honghu.villagepost.base.BaseActivity;
import com.honghu.villagepost.callback.DialogCallback;
import com.honghu.villagepost.callback.LzyResponse;
import com.honghu.villagepost.constant.Constants;
import com.honghu.villagepost.dao.manager.DbManager;
import com.honghu.villagepost.entity.User;
import com.lzy.okgo.model.Response;
import com.wuhenzhizao.titlebar.utils.ScreenUtils;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Desc:绑定手机号码
 * <p>
 * Author: [李豫]
 * Date: 2021-05-11
 * Copyright: Copyright (c) 2010-2021
 * Company: @咪咕动漫
 * Updater:
 * Update Time:
 * Update Comments:
 */
public class BandMobileActivity extends BaseActivity {

    @BindView(R.id.phone_et)
    EditText phoneEt;
    @BindView(R.id.pwd_et)
    EditText pwdEt;
    @BindView(R.id.tv_code)
    TextView sendCodeTv;
    @BindView(R.id.tv_weix_login)
    TextView tvWeixLogin;

    @BindView(R.id.title_tv)
    TextView tvWarnTitle;

    @BindView(R.id.login_tv)
    TextView tvLogin;

    @BindView(R.id.btn_back)
    ImageView mBtnBack;

    private Handler mHandler = new Handler();
    private int expired_time = 60;

    private String mOpenId;

    private boolean mNeedGoback;

    public static void self(Context context, String openid, boolean needGoback) {
        Intent intent = new Intent(context, BandMobileActivity.class);
        intent.putExtra(Constants.ITEM, openid);
        intent.putExtra(Constants.NEED_GOBACK, needGoback);
        context.startActivity(intent);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void init(Bundle savedInstanceState, View container) {
        LogUtils.d("hello");
        BarUtils.setStatusBarColor(this, getResources().getColor(R.color.colorWhite));
        tvWeixLogin.setVisibility(View.GONE);

        setMainTitle("绑定手机号码");
        tvWarnTitle.setText("手机号码绑定");
        tvLogin.setText("绑定");

        mOpenId = getIntent().getStringExtra(Constants.ITEM);
        mNeedGoback = getIntent().getBooleanExtra(Constants.NEED_GOBACK, false);

        int statusBarHeight = ScreenUtils.getStatusBarHeight(this);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mBtnBack.getLayoutParams();
        layoutParams.topMargin = statusBarHeight;
        mBtnBack.setVisibility(mNeedGoback ? View.VISIBLE : View.GONE);
        mBtnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    @OnClick({R.id.login_tv, R.id.tv_code, R.id.tv_weix_login})
    public void onViewClicked(View view) {
        String phone = phoneEt.getText().toString().trim();

        switch (view.getId()) {
            case R.id.login_tv:
                String pwd = pwdEt.getText().toString().trim();
                if (ObjectUtils.isEmpty(phone)) {
                    showToast("请输入用户名");
                    return;
                }
                if (ObjectUtils.isEmpty(pwd)) {
                    showToast("请输入密码");
                    return;
                }

                ApiService.login(this, phone, pwd, mOpenId, new DialogCallback<LzyResponse<Map<String, String>>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<Map<String, String>>> response) {
                        String accesstoken = response.body().data.get("token");
                        SPUtils.getInstance().put(Constants.TOKEN, accesstoken);
                        getUserInfo();
                    }
                });
                break;
            case R.id.tv_code:
                if (TextUtils.isEmpty(phone)) {
                    showToast("请输入手机号码");
                    return;
                }

                ApiService.verifycode(this, phone, new DialogCallback<LzyResponse<Object>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<Object>> response) {
                        sendCodeTv.setClickable(false);
                        sendCodeTv.setText(expired_time + "秒");
                        mHandler.postDelayed(runnable, 1000);

                    }
                });
                break;
//            case R.id.register_tv:
//                ActivityUtils.startActivity(this, RegisterStepPhoneActivity.class);
//                break;
//            case R.id.forget_tv:
//                ActivityUtils.startActivity(this, MainActivity.class);
//                break;
//            case R.id.pwd_visible_iv:
//                if (isVisible){
//                    pwdVisibleIv.setImageResource(R.mipmap.icon_login_eyes_normal);
//                    isVisible = false;
//                    pwdEt.setTransformationMethod(PasswordTransformationMethod.getInstance());
//                }else {
//                    pwdVisibleIv.setImageResource(R.mipmap.icon_login_eyes_click);
//                    isVisible = true;
//                    pwdEt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
//                }
//                break;
//                default:
        }
    }

    private void getUserInfo() {
        ApiService.user_info(this, new DialogCallback<LzyResponse<User>>() {
            @Override
            public void onSuccess(Response<LzyResponse<User>> response) {
                User user = response.body().data;
                if (user != null){
                    SPUtils.getInstance().put(Constants.USER_ID, user.getId());
                    initDb();
                    if (mNeedGoback) {
                        finish();
                    } else {
                        ActivityUtils.startActivity(MainActivity.class);
                    }
                }
            }
        });
    }

    /**
     * Desc:初始化数据库
     * <p>
     * Author: [李豫]
     * Date: 2021-07-15
     */
    private void initDb() {
        String userId = SPUtils.getInstance().getString(Constants.USER_ID);
        DbManager.getInstance().init(this, userId);
    }

    /**
     * 60秒倒计时
     */
    private Runnable runnable = new Runnable() {

        @Override
        public void run() {
            expired_time--;
            sendCodeTv.setText(expired_time + "秒");
            if (expired_time == 0) {
                initVcode();
                return;
            }
            mHandler.postDelayed(this, 1000);
        }
    };

    /*
     * 60秒过后初始化各状态
     */
    private void initVcode() {
        sendCodeTv.setClickable(true);
        sendCodeTv.setText("发送验证码");
    }
}
